﻿//-------------------------------------------------------------------------------------------------
// <copyright file="SplashRegistryAccess.cs" company="Anthony Adam">
// Copyright (c) Anthony Adam 2012. All rights reserved.
// </copyright>
//-------------------------------------------------------------------------------------------------
namespace SuperStarSplash
{
  using Microsoft.Win32;

  /// <summary>
  /// Utility class providing registry access functions.
  /// </summary>
  public class SplashRegistryAccess
  {
    /// <summary>
    /// Constant to the registry Software key level
    /// </summary>
    private const string Softwarekey = "Software";
    
    /// <summary>
    /// Constant for the company name in the registry
    /// </summary>
    private const string Companyname = "Anthony";
    
    /// <summary>
    /// Constant application name this splash is being used for.
    /// </summary>
    private const string Applicationname = "SuperStarRounds";

    /// <summary>
    /// Gets the registry value for a provided key, returning the provided default value if not found.
    /// </summary>
    /// <param name="key">The registry key to be retrieved</param>
    /// <param name="defaultValue">The value to return if the key is not found</param>
    /// <returns>The key value</returns>
    public static string GetStringRegistryValue(string key, string defaultValue)
    {
      var openSubKey = Registry.CurrentUser.OpenSubKey(Softwarekey, false);
      if (openSubKey == null) return defaultValue;

      var keyCompany = openSubKey.OpenSubKey(Companyname, false);
      if (keyCompany == null) return defaultValue;

      var keyApplication = keyCompany.OpenSubKey(Applicationname, true);
      if (keyApplication == null) return defaultValue;

      foreach (var keyName in keyApplication.GetValueNames())
      {
        if (keyName.Equals(key)) return keyApplication.GetValue(keyName).ToString();
      }

      return defaultValue;
    }

    /// <summary>
    /// Sets the provide key into the registry with the provided string value.
    /// </summary>
    /// <param name="key">The key name to be stored</param>
    /// <param name="stringValue">The value for the key</param>
    public static void SetStringRegistryValue(string key, string stringValue)
    {
      var keySoftware = Registry.CurrentUser.OpenSubKey(Softwarekey, true);
      var keyCompany = keySoftware?.CreateSubKey(Companyname);
      var keyApplication = keyCompany?.CreateSubKey(Applicationname);
      keyApplication?.SetValue(key, stringValue);
    }
  }
}